import lrc from "../assets/lrc/labour";
import MyImage from "./../assets/images/4409643a79630f132d31fd171bac184c.jpeg";
import MyCart from "./../assets/icons/cart.png";
export function getMovies() {
  return [
    {
      id: 1,
      title: "The Shawshank Redemption",
      year: 1994,
      genre: "Drama",
      director: "Frank Darabont",
      actors: "Tim Robbins, Morgan Freeman, Bob Gunton",
      plot: "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
    },
    {
      id: 1,
      title: "The Shawshank Redemption",
      year: 1994,
      genre: "Drama",
      director: "Frank Darabont",
      actors: "Tim Robbins, Morgan Freeman, Bob Gunton",
      plot: "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
    },
    {
      id: 1,
      title: "The Shawshank Redemption",
      year: 1994,
      genre: "Drama",
      director: "Frank Darabont",
      actors: "Tim Robbins, Morgan Freeman, Bob Gunton",
      plot: "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
    },
    {
      id: 1,
      title: "The Shawshank Redemption",
      year: 1994,
      genre: "Drama",
      director: "Frank Darabont",
      actors: "Tim Robbins, Morgan Freeman, Bob Gunton",
      plot: "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
    },
  ];
}

export function getCarts() {
  return [
    {
      productId: "PROD1234",
      productName: "Apple",
      price: "12.34",
      desc: "An apple a day keeps the doctor away",mode:'⭐机甲黄-1.2米【加粗线缆-升级线芯】',
      quantity: 3,
    },
    {
      productId: "PROD5678",
      productName: "Banana",
      price: "5.67",
      desc: "健式DFH健康设计共轭亚油酸CLA软胶囊内脏脂肪分解抗糖瘦身90粒/瓶",mode:'',
      quantity: 2,
    },
    {
      productId: "PROD9101",
      productName: "Orange",
      price: "8.90",
      desc: "⭐机甲黄-1.2米【加粗线缆-升级线芯】",mode:'⭐机甲黄-1.2米【加粗线缆-升级线芯】',
      quantity: 1,
    },
    {
      productId: "PROD1121",
      productName: "Mango",
      price: "15.00",desc: "健式DFH健康设计共轭亚油酸CLA软胶囊内脏脂肪分解抗糖瘦身90粒/瓶",mode:'',
      quantity: 4,
    },
    {
      productId: "PROD3141",
      productName: "Pineapple",
      price: "20.50",desc: "⭐机甲黄-1.2米【加粗线缆-升级线芯】",mode:'⭐机甲黄-1.2米【加粗线缆-升级线芯】',
      quantity: 2,
    },
  ];
}

export function getLrc() {
  return parserHtml();
}
/**
 * 解析lrc
 * [00:00.00] 作曲 : 周杰伦
 */
function parserHtml() {
  let _arr = lrc.split("\n");
  let _lrc = [];
  for (let i = 0; i < _arr.length; i++) {
    let _item = _arr[i].split("]");
    let _time = _item[0].replace("[", "");
    _lrc.push({
      time: parserTime(_time),
      text: _item[1],
    });
  }
  return _lrc;
}

/**
 * 解析时间
 */
function parserTime(timeStr) {
  let _arr = timeStr.split(":");
  return +_arr[0] * 60 + +_arr[1];
}

/**
 *
 * @param {*Array<obj} arr
 * @param {*} time
 */

export const findIndexByTime = (arr, time) => {
  const _index = arr.findIndex((item) => item.time > time);
  return _index === -1 ? arr.length - 1 : _index; // 如果没有找到，返回数组长度
};


// --购物车计算部分

const goods = getCarts();
console.log(goods);

class Goods {
  constructor(goods) {
    Object.defineProperty(this, "data",{
      set: function (goods) {
        this.data = goods;
      },
      get: function () {
        return goods;
      },
    })
    this._chooseNum=0;
    Object.defineProperty(this, "chooseNum",       
      {
      set: function (val) {
        this._chooseNum = val;
      },
      get: function () {
        return this._chooseNum;
      },
    })
    /**
    * 获取商品总额
    * @returns
    */
    Object.defineProperty(this, "total",{
      set: function (val) {
        this._total = val;
      },
      get: function () {
        return this.chooseNum * this.data.price;
      },
    })
    Object.seal(this);
  }
}
const g=new Goods(goods[0]);
console.log(g);
class Cart {
  constructor() {
    this.goods = goods.map((item) => new Goods(item));
    this.totalPrice = 0;
    this.deliveryFee = 15;
    this.deliveryThreshold = 50;
  }
  /**
   * 获取商品总额
   */
  getTotalPrice() {
    return this.goods.reduce((total, item) => {
      return total + item.total;
    }, 0);
  }

  /**
   * 获取商品数量
   */
  getTotalNum() {
    return this.goods.reduce((total, item) => {
      return total + item.chooseNum;
    }, 0);
  }
  /**
   * 获取起送费差额
   */
  getDeliveryDiff() {
    if (!this.hasGoodsInCart()) return 0;
    return this.deliveryThreshold - this.getTotalPrice();
  }

  /**
   *判断购物车是否有商品
   */
  hasGoodsInCart() {
    return this.getTotalNum() > 0;
  }
  // --此处代码为了避免直接操作Goods内部对象--
  /**
   * 再次封装增加某一件商品的数量
   */
  increase(index) {
    console.log(index);
    this.goods[index].increase();
  }
  /**
   * 再次封装减少某一件商品的数量
   */
  decrease(index) {
    this.goods[index].decrease();
  }
}

const main = document.createElement("div");
main.classList.add("main");

const nav = document.createElement("nav");
nav.classList.add("nav");
nav.innerHTML = `<ul><li>推荐热销</li><li>折扣</li><li>夏日冰嘟</li><li>必喝榜</li><li>进店必喝</li><li>只喝美式</li><li>酷爽特调水果冰萃</li><li>经典奶咖</li><li>创意奶咖</li><li>瑞纳冰季</li><li>不喝咖啡</li></ul>`;

//const carts = new Cart();
// carts.increase(0);
/**
 * 再次统一封装，方便统一操作、管理数据,统一汇总
 */
class UiCarts {
  constructor() {
    this.carts = new Cart();
    this.init();
    this.UiDoms = {
      minus: document.querySelectorAll(".minus"),
      plus: document.querySelectorAll(".plus"),
      totalPrice: document.querySelector(".price p"),
      totalNum: document.querySelector(".badge"),
      addToCart: document.querySelector(".add-to-cart"),
      cartCount: document.querySelector(".count"),
      submit: document.querySelector(".submit"),
    };
  }
  init() {
    this.createElement();
  }
  createElement() {
    const cartUi = document.createElement("div");
    cartUi.classList.add("cart");
    const cartsUiDom = this.carts.goods.map((item, i) => {
      return `<div class="item"><div class="thumb"><img src="${MyImage}"/></div>
            <div class="con"><h5>${item.data.productName}</h5><span>${item.data.desc}</span><p>${item.data.mode}</p>
            <div class="action"><p class="price">￥${item.data.price}</p>
            <div class="oprate"><b class="minus" data-index="${i}">-</b><b class="num">${item.chooseNum}</b>
            <b class="plus"  data-index="${i}">+</b></div></div></div></div>`;
    });
    console.log(cartsUiDom);
    cartUi.innerHTML = cartsUiDom.join("");
    const total_price = this.carts.getTotalPrice().toFixed(2);
    const status = this.carts.hasGoodsInCart() ? "active" : "";
    const settlement = document.createElement("div");
    settlement.classList.add("settlement");
    const submitText = this.carts.hasGoodsInCart()
      ? "去结算"
      : `还差￥${this.carts.getDeliveryDiff().toFixed(2)}起送`;
    settlement.innerHTML = `<div class="count"><div class="radius ${status}"><img src="${MyCart}" class="icon" alt="cart"/><i class="badge ${status}">5</i></div></div>
    <div class="price"><p>￥${total_price}</p><span>配送费：￥${this.carts.deliveryFee}</span></div>
    <button class="submit ${status}">${submitText}</button>`;

    main.appendChild(nav);
    main.appendChild(cartUi);
    document.body.appendChild(settlement);
    document.body.appendChild(main);
  }
  /**
   * 再次封装增加某一件商品的数量
   */
  increase(index) {
    console.log(index);
    this.carts.increase(index);
    this.jump(index);
  }
  /**
   * 再次封装减少某一件商品的数量
   */
  decrease(index) {
    this.carts.decrease(index);
  }
  /**
   * 摇一摇
   */
  shake() {
    this.UiDoms.cartCount.classList.add("shake");
    this.UiDoms.cartCount.addEventListener("animationend", () => {
      this.UiDoms.cartCount.classList.remove("shake");
    });
  }
  /**
   * 加入购物车动画
   */
  jump(index) {
    console.log("加入购物车动画");
    const addToCart = document.createElement("div");
    addToCart.classList.add("add-to-cart");
    const cartIcon = document.createElement("img");
    cartIcon.classList.add("icon");
    cartIcon.src = MyCart;
    addToCart.appendChild(cartIcon);
    const start = this.UiDoms.plus[index].getBoundingClientRect();
    const end = this.UiDoms.cartCount.getBoundingClientRect();
    addToCart.style.transform = `translateX(${start.x - 15}px)`;
    cartIcon.style.transform = `translateY(${start.y}px)`;
    document.body.appendChild(addToCart);
    // 强制渲染
    addToCart.clientWidth;
    addToCart.style.transform = `translateX(${end.x}px)`;
    cartIcon.style.transform = `translateY(${end.y}px)`;
    addToCart.addEventListener(
      "transitionend",
      () => {
        console.log("动画结束");
        addToCart.remove();
        this.shake();
      },
      { once: true }
    );
  }
  /**
   * 更新DOM
   */
  updatedDom() {}
}
const MyUiCarts = new UiCarts();
console.log(MyUiCarts);